﻿using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using AutoMapper;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters
{
    /// <summary>
    /// 获取轮播图信息列表命令处理
    /// </summary>
    public class GetCarouselCommandHandlter : IRequestHandler<GetCarouselCommand, ApiPaging<List<CarouelChartDtos>>>
    {
        /// <summary>
        /// 获取轮播图仓储
        /// </summary>
        private readonly IBaseRepository<CarouelChartModel> _carouselRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<GetCarouselCommandHandlter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// </summary>
        /// <param name="carouselRepository">获取轮播图仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志</param>
        public GetCarouselCommandHandlter(
            IBaseRepository<CarouelChartModel> carouselRepository,
            IMapper mapper,
            ILogger<GetCarouselCommandHandlter> logger)
        {
            _carouselRepository = carouselRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiPaging<List<CarouelChartDtos>>> Handle(GetCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
            
                // 获取所有轮播图数据
                var query = _carouselRepository.GetAll().AsNoTracking();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.Title))
                {
                    query = query.Where(x => x.CarouelChartTitle.Contains(request.Title));
                    
                }

                if (request.Status.HasValue)
                {
                    query = query.Where(x => x.ststus == request.Status.Value);
                    
                }

                // 应用时间范围条件
                if (!string.IsNullOrEmpty(request.startTime) && DateTime.TryParse(request.startTime, out var startTime))
                {
                    query = query.Where(x => x.CreatedTime >= startTime);
                }

                if (!string.IsNullOrEmpty(request.endTime) && DateTime.TryParse(request.endTime, out var endTime))
                {
                    query = query.Where(x => x.CreatedTime <= endTime);
                    
                }

                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取总数量
                var totalCount = query.Count();
                // 计算分页信息
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
                var skip = (request.PageIndex - 1) * request.PageSize;

                // 获取分页数据
                var pagedData = query.Skip(skip).Take(request.PageSize).ToList();
        
                // 映射到DTO
                var carouselDtos = _mapper.Map<List<CarouelChartDtos>>(pagedData);

 
                return new ApiPaging<List<CarouelChartDtos>>
                {
                    code = ResultEnumCode.Ok,
                    message = "轮播图列表获取成功",
                    data = carouselDtos,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图列表过程中发生异常，页码：{PageIndex}，每页数量：{PageSize}", 
                    request.PageIndex, request.PageSize);

                return new ApiPaging<List<CarouelChartDtos>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取轮播图列表失败：{ex.Message}",
                    data = new List<CarouelChartDtos>(),
                    TotalCount = 0,
                    PageCount = 0,
                  
                };
            }
        }
    }
}
